package org.amse.Archiver.algorithm;
import java.io.*;
public class PrintCoderWriter implements ICoder {
	private int [] myStatistic;
	private final PrintWriter myOutputFile;
    private final FileInputStream myInputFile;
    private final String in;
	private byte[][] myCodeArray;
	private int mySymNum;
	private File output;
	
	public PrintCoderWriter(File input, byte[][] codeArray, int[] stat, int size) throws IOException {
	    myCodeArray = codeArray;
		myInputFile = new FileInputStream(input);
		output = new File(getNewName(input) + ".huf");
		myOutputFile = new PrintWriter(new FileWriter(output));
		myStatistic = stat;
		mySymNum = size;
		in = input.getName();
	}
	
	public File getOutFile(){
		return output;
	}
	
	private String getNewName(File f){
		StringBuffer name = new StringBuffer();
		name.append(f.getAbsolutePath());
		name.delete(name.lastIndexOf("."), name.length());
    	return name.toString();
    }
	
	public void encode() throws IOException {
		int ch;
		writeTechInf();
		while ((ch = myInputFile.read()) != -1) {
		    int i = ch; int j = 0;
			while(myCodeArray[i][j] != -1) {
				myOutputFile.print(myCodeArray[i][j++] + " ");
			}
		}
		myInputFile.close();
		myOutputFile.close();
	}

	
	public void writeTechInf() throws IOException {
		myOutputFile.println(in);
		myOutputFile.println(mySymNum);
		for (int i = 0; i < myStatistic.length; i++) {
		    myOutputFile.print(myStatistic[i] + " ");
		}
		myOutputFile.println();
	}
   
}
